package ProtocolResolution

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"lht-go-plugins/LhtPlugins/Sql/sqlite"
	"log"
	"net/http"
)

type Hub struct {
	clients   map[*websocket.Conn]bool
	broadcast chan sqlite.OCMessage
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

func NewHub() *Hub {
	return &Hub{
		clients:   make(map[*websocket.Conn]bool),
		broadcast: make(chan sqlite.OCMessage, 100),
	}
}

func (h *Hub) Broadcast(msg sqlite.OCMessage) {
	data, _ := json.Marshal(msg)
	for client := range h.clients {
		err := client.WriteMessage(websocket.TextMessage, data)
		if err != nil {
			client.Close()
			delete(h.clients, client)
		}
	}
}

func UpgradeWebSocket(w http.ResponseWriter, r *http.Request, hub *Hub) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	hub.clients[conn] = true

	// 客户端连接上就发一次最新数据（可选）
	// go func() { conn.WriteJSON(latestMsg) }()

	for {
		_, _, err := conn.ReadMessage() // 长连接只发不读
		if err != nil {
			delete(hub.clients, conn)
			conn.Close()
			break
		}
	}
}
